import React, { Component } from 'react';
import Item from './Item';

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as cartActions from "../store_redux/actions/cart.actions";

class Cart extends Component {
    componentDidMount() {
        const { loadCarts } = this.props;
        loadCarts();
    }
    render() {
        const { items, curApples, eatenApples, GET_APPLE, LOAD_APPLES } = this.props;
        return (
            <section className="cart-wrapper">
                <div className="header">
                    <h2>Apple Cart Redux</h2>
                </div>
                <div className="computed">
                    <div className="left">
                        <h3>Current: </h3>
                        <h4>{curApples}</h4>
                    </div>
                    <div className="right">
                        <h3>Eaten: </h3>
                        <h4>{eatenApples}</h4>
                    </div>
                </div>
                <div className="items-wrapper">
                    {
                        items.length > 0 ? items.map(item => {
                            if (!item.isEaten) return <Item data={item} key={item.id} />
                        }) : "No Apples"
                    }
                </div>
                <div className="btn-area">
                    <button className="btn" onClick={GET_APPLE}>Get an apple</button>
                    <button className="btn" onClick={LOAD_APPLES}>Refresh Data</button>
                </div>
            </section>
        )
    }
}

const mapStateToProps = (state) => ({
    items: state.cart.apples,
    curApples: state.cart.curApples,
    eatenApples: state.cart.eatenApples
});

const mapDispatchToProps = (dispatch) => ({
    ...bindActionCreators(cartActions, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(Cart);